package com.example.managemyself.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Spring Security 安全配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF保护
            .csrf().disable()
            
            // 配置CORS
            .cors().configurationSource(corsConfigurationSource())
            
            .and()
            
            // 配置会话管理为无状态
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            
            .and()
            
            // 配置请求授权
            .authorizeRequests()
                // 允许健康检查接口无需认证
                .antMatchers("/api/health/**").permitAll()
                .antMatchers("/api/db-status").permitAll()
                .antMatchers("/api/info").permitAll()
                
                // 允许用户相关API无需认证
                .antMatchers("/api/users/register", "/api/users/login").permitAll()
                .antMatchers("/api/logout").permitAll()
                .antMatchers("/api/user").permitAll()
                .antMatchers("/api/reset-password").permitAll()
                .antMatchers("/api/verify-code").permitAll()
                
                // 允许任务相关API（暂时开放，后续可加认证）
                .antMatchers("/api/tasks/**").permitAll()
                
                // 允许健康数据相关API（暂时开放，后续可加认证）
                .antMatchers("/api/health-data/**").permitAll()
                
                // 允许H2控制台访问（仅开发环境）
                .antMatchers("/h2-console/**").permitAll()
                
                // 其他所有请求都需要认证
                .anyRequest().authenticated()
            
            .and()
            
            // 禁用X-Frame-Options以允许H2控制台
            .headers().frameOptions().disable();
    }
    
    /**
     * 密码编码器Bean
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    /**
     * CORS配置
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        // 允许所有来源
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        
        // 允许的HTTP方法
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        
        // 允许的请求头
        configuration.setAllowedHeaders(Arrays.asList("*"));
        
        // 允许发送凭证
        configuration.setAllowCredentials(true);
        
        // 预检请求的缓存时间
        configuration.setMaxAge(3600L);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        
        return source;
    }
} 